# encoding=utf8
import sys 
import importlib
import modelft
import time
import random
reload(sys)
sys.setdefaultencoding('utf8')

class obdMessageAnalysis: #协议解析
    protocol = ""
    mark = ""
    result = []
    def __init__(self):
        pass
    def doGet(self,pro_id,pro_data):
        self.protocol = pro_data
        self.mark = pro_id
        model = ModelInit()
        self.result = model.reflection(self.protocol,self.mark) #python反射技术，这里根据消息ID动态导入需要使用的解析对应ID的的库
        #for i in range(len(self.result)):
           #print "i=%d,doget:%s",i,self.result[i]
        #return self.result #list
        self.result.reverse()
        this_time=(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        this_number=str(random.randrange(0,65535))
        self.result.append("本次解析时间：" + this_time + "  解析随机码：" +this_number + '\n \n')
        self.result.reverse()
        return "".join(self.result)#str

class ModelInit:
    header =[]
    result =[]
    protocolStr =""
    revMark = ""
    def __init__(self):
        pass
    def reflection(self,protocol,mark):
        self.protocolStr = protocol
        self.revMark = mark
        if (self.protocolStr.strip() != "" and len(self.protocolStr) > 30 ):
            print "使用808协议分析"
            oBD17691Message = OBD17691Message()
            self.protocolStr = oBD17691Message.getMessageHead(self.protocolStr)#protocolStr  17691协议消息体
            header = oBD17691Message.getResult()# #header 消息头（解析后的结果）
            try:
                nameJonit='OBD_'+self.revMark
                print(nameJonit)
                md_Name=importlib.import_module("."+nameJonit,"app.model17691")
                print(md_Name)
                cl_Name=getattr(md_Name,nameJonit)#获得类
                cl_Name_Obj =cl_Name()#实例化对象
                cl_Name_Obj.LogicAisle(self.protocolStr, header)#调用LogicAisle方法
                self.result = cl_Name_Obj.result #在对象上获取此字段的值
                for i in range(len(self.result)):
                    print ("jt_reflection:"+self.result[i])
                return self.result
            except ImportError:
                print("file model17691/%s.py is not existed." %nameJonit)
        else:
            return self.result.append("输入报文有误，请重新输入")

class OBD17691Message:
    protocolStr=""#报文
    result=[]
    startFlag=""#起始符
    cmdUnit=""#命令单元
    Vin=""#车辆识别号
    softVersion=""#终端软件版本号
    encryptionMode=""#数据加密方式
    dataUnitLength=""#数据单元长度
    dataUnit=""#数据单元
    checkSum=""#校验码
    information=["起始符:", "命令单元:", "车辆识别号:", "终端软件版本号:", "数据加密方式:", "数据单元长度:", "数据单元:", "校验码:"]
    def getMessageHead(self,protocolStr):
        self.protocolStr = protocolStr
        print type(self.protocolStr)
        self.setStartFlag(self.protocolStr[0:4])
        self.setCmdUnit(self.protocolStr[4:6])
        self.setVin(self.protocolStr[6:40])
        self.setSoftVersion(self.protocolStr[40:42])
        self.setEncryptionMode(self.protocolStr[42:44])
        self.setDataUnitLength(self.protocolStr[44:48])
        self.setDataUnit(self.protocolStr[48:len(self.protocolStr)-2])
        self.setCheckSum(self.protocolStr[-2:])
        self.protocolStr =self.dataUnit
        print("self.getDataUnit/%s" %self.protocolStr)
        return self.protocolStr
    def getResult(self):
        self.result=[]
        for i in range(len(self.information)):
            if (i==0):
                self.result.append(self.information[i] + self.startFlag + '\n')
            elif (i==1):
                self.result.append(self.information[i] + self.cmdUnit + '\n')
            elif(i==2):
                self.result.append(self.information[i] + self.Vin + '\n')
            elif(i==3):
                self.result.append(self.information[i] + self.softVersion + "\n")
            elif(i==4):
                self.result.append(self.information[i] + self.encryptionMode + "\n")
            elif(i==5):
                self.result.append(self.information[i] + self.dataUnitLength + "\n")
            elif(i==6):
                self.result.append(self.information[i] + self.dataUnit + "\n")
            elif(i==7):
                self.result.append(self.information[i] + self.checkSum + "\n")
            else:
                print"getResult"
        return self.result

    def getStartFlag(self):
        return self.startFlag
    def setStartFlag(self,startFlag):
        self.startFlag = startFlag
    def getCmdUnit(self):
        return self.cmdUnit
    def setCmdUnit(self,cmdUnit):
        self.cmdUnit =cmdUnit
    def getVin(self):
        return self.Vin
    def setVin(self,Vin):
        self.Vin =Vin
    def getSoftVersion(self):
        return self.softVersion
    def setSoftVersion(self,softVersion):
        self.softVersion =softVersion
    def getEncryptionMode(self):
        return self.encryptionMode
    def setEncryptionMode(self,encryptionMode):
        self.encryptionMode =encryptionMode
    def getDataUnitLength(self):
        return self.dataUnitLength
    def setDataUnitLength(self,dataUnitLength):
        self.dataUnitLength =dataUnitLength
    def getDataUnit(self):
        return self.dataUnit
    def setDataUnit(self,dataUnit):
        self.dataUnit =dataUnit
    def getCheckSum(self):
        return self.checkSum
    def setCheckSum(self,checkSum):
        self.checkSum =checkSum
